﻿using BTechBids.Web.IDataAdapters.Adapters;
using BTechBids.Web.IDataAdapters.Interfaces;
using BTechBids.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace BTechBids.Web.Controllers
{
    [Authorize]
    public class UserController : ApiController
    {
        IItemAdapter _adapter;

        public UserController()
        {
            _adapter = new ItemAdapter();
        }


        // GET api/user/winitems/
        [ActionName("winitems")]
        public IHttpActionResult GetUserWins()
        {
            string username = User.Identity.GetUserName();
            List<ItemUserVM> userItems = _adapter.GetUserWins(username);
            return Ok(userItems);
        }

        // GET api/user/detail/
        [ActionName("detail")]
        public IHttpActionResult GetUserDetails()
        {
            string username = User.Identity.GetUserName();
            UserVM uservm = _adapter.UpdateUserAccount(username);
            return Ok(uservm);
        }

        // PUT api/user/addbids/:count
        [ActionName("addbids")]
        public IHttpActionResult PutUserBids(int id)
        {
            string username = User.Identity.GetUserName();
            UserVM uservm = _adapter.UpdateUserAccount(username, addBids:id);
            return Ok(uservm);
        }

        // PUT api/user/addmoney/:money
        [ActionName("addsubtractmoney")]
        public IHttpActionResult PutAddOrSubtractUserMoney(double id)
        {
            string username = User.Identity.GetUserName();
            UserVM uservm = _adapter.UpdateUserAccount(username, addOrSubtractMoney:id);
            return Ok(uservm);
        }

        // PUT api/user/buybids
        [ActionName("buybids")]
        public IHttpActionResult PutBuyBids([FromBody] BuyBidsVM bbvm)
        {
            string username = User.Identity.GetUserName();
            UserVM uservm = _adapter.UpdateUserAccount(username);
            if (uservm.Wallet < bbvm.Cost)
            {
                return NotFound();
            }
            uservm = _adapter.UpdateUserAccount(uservm.UserName, bbvm.Bids, -bbvm.Cost);
            return Ok(uservm);
        }

        // PUT api/user/buyitems
        [ActionName("buyitems")]
        public IHttpActionResult PutBuyItems()
        {
            string username = User.Identity.GetUserName();
            _adapter.SettleUserAccount(username);
            UserVM uservm = _adapter.UpdateUserAccount(username);
            return Ok(uservm);
        }

    }
}
